<?php
// 本类由系统自动生成，仅供测试用途
class ApiAction extends Action {

	function doGet($cid){
	$signature=I('signature');
		$timestamp=I('timestamp');
		$nonce=I('nonce');

		$profile = M("profile")->where(array('id' =>$cid))->find();
		$token=$profile["token"];

		$arr=array($token,$timestamp,$nonce);
		sort($arr, SORT_STRING);
		$arr = implode( $arr );
		$arr=sha1($arr);
		$echostr=I("echostr");
		if($arr==$signature){
			echo $echostr;
		}
	}

	function doPost($cid){
		$string = file_get_contents('php://input', 'r');
		$xml = simplexml_load_string($string);
		//解析结果
		$ToUserName =(string) $xml->ToUserName;
		$FromUserName =(string) $xml->FromUserName;
		$CreateTime =(string) $xml->CreateTime;
		$MsgType =(string) $xml->MsgType;
		$Event =(string) $xml->Event;
		$EventKey =(string) $xml->EventKey;
		$resp="";

		$db = M('profile');
		$profile= $db->where(array('id' => $cid))->find();
		$gzhId=$profile["gzhId"];
		$wxid=$FromUserName;


		$xml="<xml>";
		$xml=$xml."<ToUserName><![CDATA[".$wxid."]]></ToUserName>";
		$xml=$xml."<FromUserName><![CDATA[".$gzhId."]]></FromUserName>";
		$xml=$xml."<CreateTime>".time()."</CreateTime>";
		$xml=$xml."<MsgType><![CDATA[text]]></MsgType>";
		$xml=$xml."<Content><![CDATA[hello]]></Content>";
		$xml=$xml."<FuncFlag>0</FuncFlag>";
		$xml=$xml."</xml>";

		echo $xml;die;

		if(strtoupper($MsgType) == "LOCATION"){
			$lat=(string) $xml->Location_X;
			$lng=(string) $xml->Location_Y;
			$locationReply =  $profile["locationReply"];
			if(strlen($locationReply)>0){
				$e= substr($locationReply,strlen($locationReply)-1,strlen($locationReply));
				$s= substr($locationReply,0,1);
				if($s=="{"&&$e=="}"){
					$obj=jsonToArr($locationReply);
					$type = $obj["type"];
					switch ($type){
						case 1:
							$locationReply = $obj["value"];
							$funcFlag="0";
							$msgType="text";
							$resp=$this->createResp($locationReply,$funcFlag,$msgType,$gzhId,$wxid);
							break;
						case 2:
							$articleId = $obj["value"];
							$resp=$this->createArticleRespLatLng($articleId,$gzhId,$wxid,$lat,$lng);
							break;
					}
				}else{
					$funcFlag="0";
					$msgType="text";
					$resp=$this->createResp($locationReply,$funcFlag,$msgType,$gzhId,$wxid);
				}
			}else{
				//无消息
			}
		}

		if(!$resp){//点击按钮
			if(strtoupper($Event)=="CLICK"){
				if(startsWith(strtolower($EventKey),"view_msg_")){
					$articleId = substr($EventKey,9);
					$resp=$this->createArticleResp($articleId,$gzhId,$wxid);
				}
			}
		}
		
		if(!$resp){//图文或文本信息回复
			$replyContext = $profile["messageReply"];
			if(strlen($replyContext)>0){
				$e= substr($replyContext,strlen($replyContext)-1,strlen($replyContext));
				$s= substr($replyContext,0,1);
				if($s=="{"&&$e=="}"){
					$obj=jsonToArr($replyContext);
					$type = $obj["type"];
					switch ($type){
						case 1:
							$replyContext = $obj["value"];
							$funcFlag="0";
							$msgType="text";
							$resp=$this->createResp($replyContext,$funcFlag,$msgType,$gzhId,$wxid);
							break;
						case 2:
							$articleId = $obj["value"];
							$resp=$this->createArticleResp($articleId,$gzhId,$wxid);
							break;
					}
				}else{
					$funcFlag="0";
					$msgType="text";
					$resp=$this->createResp($replyContext,$funcFlag,$msgType,$gzhId,$wxid);
				}
			}else{
				//无消息
			}
		}
		header("Content-Type:text/html;charset=UTF-8");
		echo  $resp;
	}
	//测试json字符串解析
	public function test(){
		$db = M('profile');
		$profile= $db->where(array('id' => 19))->find();
		$locationReply =  $profile["locationReply"];
		if(strlen($locationReply)>0){
			$e= substr($locationReply,strlen($locationReply)-1,strlen($locationReply));
			$s= substr($locationReply,0,1);
			if($s=="{"&&$e=="}"){
				$obj=jsonToArr($locationReply);
				header("Content-Type:text/html;charset=UTF-8");
				echo '中国';
				p($obj);
			}else{
				echo 'error1';
			}
		}else{
			echo '$locationReply len =0';
		}
		die;
	}

	public function main(){
		// 		$cid= $_GET['_URL_'][3]; 		//$url_this = $_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF']; 从中截取
		$cid=19;
		if(IS_POST){
			$this->doPost($cid);
		}else if (IS_GET){
			$this->doGet($cid);
		}else{
			echo 'error';die();
		}
	}

	//创建纯文本消息
	function createResp($replyContext="",$funcFlag="0",$msgType="text",$gzhId,$wxid){
		$xml="<xml>";
		$xml=$xml."<ToUserName><![CDATA[".$wxid."]]></ToUserName>";
		$xml=$xml."<FromUserName><![CDATA[".$gzhId."]]></FromUserName>";
		$xml=$xml."<CreateTime>".time()."</CreateTime>";
		$xml=$xml."<MsgType><![CDATA[".$msgType."]]></MsgType>";
		$xml=$xml."<Content><![CDATA[".$replyContext."]]></Content>";
		$xml=$xml."<FuncFlag>".$funcFlag."</FuncFlag>";
		$xml=$xml."</xml>";
		return $xml;
	}
	//创建图文消息
	function createArticleResp($articleId,$gzhId,$wxid){
		$db=M("article");
		$articles=$db->where("graphic_id=".$articleId)->select();
		$xml="<xml>";
		$xml=$xml."<ToUserName><![CDATA[".$wxid."]]></ToUserName>";
		$xml=$xml."<FromUserName><![CDATA[". $gzhId."]]></FromUserName>";
		$xml=$xml."<CreateTime>".time()."</CreateTime>";
		$xml=$xml."<MsgType><![CDATA[news]]></MsgType>";
	
		$xml=$xml."<ArticleCount>".count($articles)."</ArticleCount>";
		$xml=$xml."<Articles>";
		foreach ($articles as $art){
			$xml=$xml."	<item>";
			$xml=$xml."		<Title><![CDATA[".$art["head_title"]."]]></Title> ";
			$xml=$xml."		<Description><![CDATA[".$art["summary"]."]]></Description>";
			$xml=$xml."		<PicUrl><![CDATA[".C("httpPath").U('File/downLoad')."/id/".$art["img_id"]."]]></PicUrl>";

//            $xml=$xml."		<PicUrl><![CDATA[http://myyidan.sinaapp.com/Public/Uploads/1234.png]]></PicUrl>";
	
			if (strtolower($art["type"])=="article")
			{// 如果是文章消息，则直接返回访问文章的url
				//$xml=$xml."		<Url><![CDATA[".U('File/downLoad')."/id/".$art["id"]."]]></Url>";
			}
			else if (strtolower($art["type"])=="link")
			{//如果是连接消息，则拼接参数
				$url = $art["linkUrl"];
				if ($url)
				{
					$ts =time();
					$arr=array($wxid,$gzhId,$ts);
					sort($arr);
					$str="";
					foreach ($arr as $a ){
						$str.+$a;
					}
					$token =encrypt($str);
					if (strpos($url,"?"))
					{
						$url=$url."&";
					}
					else
					{
						$url=$url."?";
					}
					
					$url=$url."wxid=".$wxid."&gzhId=".$gzhId."&token=".$token."&ts=".time();
					$xml=$xml."		<Url><![CDATA[".$url."]]></Url>";
				}
				$xml=$xml."	</item>";
			}
		}
		$xml=$xml."</Articles>";
		$xml=$xml."</xml> ";
		return $xml;
	}
	
	//创建图文消息
	function createArticleRespLatLng($articleId,$gzhId,$wxid,$lat,$lng){
		$db=M("article");
		$articles=$db->where("graphic_id=".$articleId)->select();
		$xml="<xml>";
		$xml=$xml."<ToUserName><![CDATA[".$wxid."]]></ToUserName>";
		$xml=$xml."<FromUserName><![CDATA[". $gzhId."]]></FromUserName>";
		$xml=$xml."<CreateTime>".time()."</CreateTime>";
		$xml=$xml."<MsgType><![CDATA[news]]></MsgType>";
	
		$xml=$xml."<ArticleCount>".count($articles)."</ArticleCount>";
		$xml=$xml."<Articles>";
		foreach ($articles as $art){
			$xml=$xml."	<item>";
			$xml=$xml."		<Title><![CDATA[".$art["head_title"]."]]></Title> ";
			$xml=$xml."		<Description><![CDATA[".$art["summary"]."]]></Description>";

            $xml=$xml."		<PicUrl><![CDATA[http://myyidan.sinaapp.com/Public/Uploads/1234.png]]></PicUrl>";

//			$xml=$xml."		<PicUrl><![CDATA[".C("httpPath").U('File/downLoad')."/id/".$art["img_id"]."]]></PicUrl>";
	
			if (strtolower($art["type"])=="article")
			{// 如果是文章消息，则直接返回访问文章的url
				$xml=$xml."	<Url><![CDATA[".$art["summary"]."<br/>".$art["main_text"]."<br/>". $art["original_link"]."]]></Url></item>";
			}
			else if (strtolower($art["type"])=="link")
			{//如果是连接消息，则拼接参数
				$url = $art["linkUrl"];
				if ($url)
				{
					$ts =time();
					$arr=array($wxid,$gzhId,$ts);
					sort($arr);
					$str="";
					foreach ($arr as $a ){
						$str.+$a;
					}
					$token =encrypt($str);
					if (strpos($url,"?"))
					{
						$url=$url."&";
					}
					else
					{
						$url=$url."?";
					}
					if($lat&&$lng){
						$url=$url."wxid=".$wxid."&gzhId=".$gzhId."&token=".$token."&lat=".$lat."&lng=".$lng."&ts=".time();
					}else{
						$url=$url."wxid=".$wxid."&gzhId=".$gzhId."&token=".$token."&ts=".time();
					}
					
					$xml=$xml."		<Url><![CDATA[".$url."]]></Url>";
				}
				$xml=$xml."	</item>";
			}
		}
		$xml=$xml."</Articles>";
		$xml=$xml."</xml> ";
		return $xml;
	}
}